package com.zhangsun.newMvvm.adapter;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import com.zhangsun.newMvvm.R;
import com.zhangsun.newMvvm.base.bean.ResponseData;
import com.zhangsun.newMvvm.base.enums.PagingLoadTypeEnum;
import com.zhangsun.newMvvm.databinding.UserItemBinding;
import com.zhangsun.newMvvm.handler.UserEventHandlers;
import com.zhangsun.newMvvm.model.bean.UserBean;

import java.util.ArrayList;
import java.util.List;

public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {

    private Context context;

    private List<UserBean> users;

    public UserAdapter(Context context) {
        this.context = context;
        this.users = new ArrayList<>();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        LayoutInflater inflater = LayoutInflater.from(context);
        UserItemBinding userItemBinding = DataBindingUtil.inflate(inflater, R.layout.item_user, viewGroup, false);
        return new ViewHolder(userItemBinding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
        UserBean user = users.get(position);
        viewHolder.userItemBinding.setUserBean(user);
        viewHolder.userItemBinding.setUserHandler(new UserEventHandlers(this.context));
        viewHolder.userItemBinding.executePendingBindings();
    }

    @Override
    public int getItemCount() {
        return users.size();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    public void setUsers(PagingLoadTypeEnum pagingLoadTypeEnum, List<UserBean> users) {
        if (!PagingLoadTypeEnum.MORE.equals(pagingLoadTypeEnum)) {
            this.users.clear();
        }
        this.users.addAll(users);
        notifyDataSetChanged();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        private UserItemBinding userItemBinding;

        ViewHolder(UserItemBinding userItemBinding) {
            super(userItemBinding.getRoot());
            this.userItemBinding = userItemBinding;
        }
    }

}
